<?php
/**
 * Model class for content table
 * @author Antonello D'Ippolito (http://www.antonellodippolito.com)
 */
class Content extends Zend_Db_Table_Abstract {
    protected $_name = 'ad_content';
    protected $_primary = 'id';
    
    /**
     * If $data[id] doesn't exist inserts a new record, otherwise updates the existing
     * record with the new values present in $data
     * @param Array $data
     * @return int Number of affected rows
     */
    public function save($data) {
        if(isset($data["id"])) {
            $result = $this->read($data["id"]);
            if(!empty($result)) {
                return $GLOBALS["db"]->update('ad_content', $data, "id = ".$data["id"]);
            }
            else {
                $data["creation_date"] = time();
                return $GLOBALS["db"]->insert('ad_content', $data);
            }
        }
        else {
            $data["creation_date"] = time();
            return $GLOBALS["db"]->insert('ad_content', $data);
        }
    }
    
    /**
     * Returns an array with the content info 
     * @param int $contentID Contend ID
     * @return Array Content info 
     */
    public function read($contentID) {
        $res = $this->find($contentID)->toArray();
        return $res[0];
    }
    
    /**
     * List all the pages in the db recursively ordered by parent id and order
     * @param int $parentID Parent ID
     * @param array $pages Array that is filling with pages
     * @param int $level Depth level
     * @return array Associative array with all the pages
     */
    public function listPages($parentID=0, &$pages=array(), $level=0) {
        $query = "SELECT * FROM ad_content 
                  WHERE menu_parent_id = $parentID 
                  ORDER BY menu_order, title";
        $level++;
        $stmt = $GLOBALS["db"]->query($query);
        $rows = $stmt->fetchAll();
        if(!empty($rows)) {
            foreach ($rows as $page) {
                $page["level"] = $level;
                $pages[] = $page;
                $this->listPages($page["id"], $pages, $level);
            }
        }
        return $pages;
    }
 
}
?>
